﻿using System;
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.IO;
using System.Linq;
using System.Linq;
using System.Web;
using System.Web;
using System.Web.Mvc;
using MezmurStore2.Models;
using MezmurStore2.Utility;
using System.Data.Entity;
namespace MezmurStore2.Controllers
{
    [Authorize]
    public class AlbumManagerController : BaseController
    {
        private MezmurStoreEntities db = new MezmurStoreEntities();

        //
        // GET: /AlbumManager/

        public ViewResult Index()
        {
            var userId = this.CurrentUser.ProviderUserKey.ToString();
            var albums = db.Albums.Include(a => a.Tracks).Where( a=> a.OwnerUserId == userId);
            return View(albums.ToList());
        }

       

        //
        // GET: /AlbumManager/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /AlbumManager/Create

        [HttpPost]
        public ActionResult Create(Album album, HttpPostedFileBase posterImage)
        {
            if (ModelState.IsValid)
            {
                album.Id = Guid.NewGuid();
                Stream inputStream;
                string inputFileName;
                if (posterImage == null)
                {
                    inputFileName = album.Poster;
                    inputStream = new FileStream(Server.MapPath(album.Poster), FileMode.Open, FileAccess.Read);
                }
                else
                {
                    inputFileName = posterImage.FileName;
                    inputStream = posterImage.InputStream;
                }

                string[] extensionParts = inputFileName.Split('.');
                string fileExt = extensionParts.Last();
                var fileName = string.Format("{0}.{1}", Guid.NewGuid(), fileExt);
                var uploadUri = new BlobStoreFileManager().UploadFile(inputStream, "media", fileName, null);
                album.Poster = uploadUri;
                album.ReleaseDate = DateTime.Now;
                album.OwnerUserId = this.CurrentUser.ProviderUserKey.ToString();
                db.Albums.Add(album);
                db.SaveChanges();
                return RedirectToAction("UploadTrack", new { albumId = album.Id.ToString()});  
            }

            //ViewBag.ArtistId = new SelectList(db.Artists, "Id", "Name", album.ArtistId);
            return View(album);
        }

        // GET: /AlbumManager/UploadTrack
        public ActionResult UploadTrack(string albumId)
        {
            var album = db.Albums.Find(new Guid(albumId));
            return View(album);
        }

        [HttpPost]
        public void UploadTrack(HttpPostedFileBase file, FormCollection forms)
        {
            // Read album info.
            Id3Lib.ID3v1 id3 = new Id3Lib.ID3v1();
            id3.Deserialize(file.InputStream);

            string albumId = forms.Get("albumId");
            var album = db.Albums.Find(new Guid(albumId));

            string[] extensionParts = file.FileName.Split('.');
            string fileExt = extensionParts.Last();
            var fileId = Guid.NewGuid();
            var fullName = string.Format("{0}.{1}", fileId, fileExt);
            var fileUri = new BlobStoreFileManager().UploadFile(file.InputStream, "media", fullName, "audio/mpeg");

            var track = new Track();
            track.Id = fileId;
            track.FilePath = fileUri;
            track.Name = id3.Song;
            track.FileSize = file.ContentLength;
            track.ArtistName = id3.Artist;
            album.Tracks.Add(track);
            db.SaveChanges();
        }
        //
        // GET: /AlbumManager/Edit/5
 
        public ActionResult Edit(Guid id)
        {
            Album album = db.Albums.Include("Tracks").First(a => a.Id == id);
            return View(album);
        }

        //
        // POST: /AlbumManager/Edit/5

        [HttpPost]
        public ActionResult Edit(Album album)
        {
            if (ModelState.IsValid)
            {
                db.Entry(album).State = EntityState.Modified;
                foreach(var track in album.Tracks)
                {
                    db.Entry(track).State = EntityState.Modified;
                }
                
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(album);
        }

        //
        // GET: /AlbumManager/Delete/5
 
        public ActionResult Delete(Guid id)
        {
            Album album = db.Albums.Find(id);
            return View(album);
        }


        //
        // POST: /AlbumManager/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(Guid id)
        {
            Album album = db.Albums.Include(a => a.Tracks).First(a => a.Id == id);
            album.Tracks.ForEach(t => db.Tracks.Remove(t));
            db.Albums.Remove(album);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult DeleteTrack(Guid id, Guid trackId)
        {
            Album album = db.Albums.Include(a => a.Tracks).First(a => a.Id == id);
            Track track = album.Tracks.First(t => t.Id == trackId);
            album.Tracks.Remove(track);
            db.Entry(album).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Edit", new {id = id });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}